package com.qc.common;

public class Session {

	public static final String TOKEN_PREFIX = "[TOKEN]";
	public static final String SECRET_PREFIX = "[SECRET]";
	public static final String User_PREFIX = "[USER]";
//	protected long userId;

	private Session(){}
	
//	private HttpServletResponse response;
//	private HttpServletRequest request;
	
	public static String getMobileToken(long uid){
		long time = System.currentTimeMillis();
		long ranLong = time + uid;
					
		String strId = String.format("%020d", ranLong);
		String strVal = WebUtil.hashEncrypt(strId);
		
		return new StringBuilder().append(time).append(":").append(strVal).append(strId).toString(); 
	}
	
	public static boolean isValidMobileToken(String mobileToken){
		if(mobileToken == null || mobileToken.length()!=66 || mobileToken.indexOf(":")!=13) return false;
		return true;
	}
	
	public static String getMobileTokenValue(long time, long uid){
		long ranLong = time + uid;
				
		String strId = String.format("%020d", ranLong);
		String strVal = WebUtil.hashEncrypt(strId);
		
		return new StringBuilder().append(strVal).append(strId).toString();
	}
	
//	public static Session getInstance(HttpServletRequest request, HttpServletResponse response) throws BusinessException{
//		
//		Session s = new Session();
//		s.response = response;
//		
//		Object ouId = request.getAttribute(ServiceConstants.USER_ID.toString());
//		if(ouId != null)
//		{
//			s.userId = ((Long)ouId).longValue();
////			if(ConfigurationManager.Config.IsDebugMode)
//				WebUtil.logDebug("Find user id in request" + s.userId);
//			return s;
//		}
//		
//		Cookie [] cookies = request.getCookies();
//		if(cookies != null){
//			for(Cookie c : cookies){
//				if(c.getName() == null) continue;
//				
//				if(c.getName().startsWith(ServiceConstants.SessionID.toString())){
//					String val = c.getValue();
//					
//					long time = Long.parseLong(c.getName().replace(ServiceConstants.SessionID.toString(),""));
//					long mixId = Long.parseLong(val.substring(val.length() - 20, val.length()));
//					String strVal = val.substring(0, val.length()-20);
//					
//					String strId = String.format("%020d", mixId);
//										
//					String hash = WebUtil.hashEncrypt(strId);
//					if(!strVal.equals(hash)){
//						WebUtil.logDebug("user id is not valid("+strId+"):"+strVal + " hash:"+hash);
//						throw new CookieNotValidException("user id is not valid("+strId+"):"+strVal + " hash:"+hash);
//					}
//					
//					s.userId = mixId - time;
//					request.setAttribute(ServiceConstants.USER_ID, new Long(s.userId));
//				}
//			}
//		}
////		if(ConfigurationManager.Config.IsDebugMode) 
//			WebUtil.logDebug("read user id from cookie" + s.userId);
//		return s;
//	}
	
//	public static Session setInstance(HttpServletRequest request, HttpServletResponse response, long userId) throws BusinessException{
//		
//		Session s = new Session();
//		s.response = response;
//		s.request = request;
//		
//		s.setUserId(userId);
//		return s;
//	}
	
//	public static void saveSession(String key, String value) throws Exception{
//		SessionEntity session = new SessionEntity(key, value);
//		DAOFactory.getSessionDAO().saveSession(session);
//	}
//	public static void saveSession(SessionEntity session) throws Exception{
//		DAOFactory.getSessionDAO().saveSession(session);
//	}
//	
//	public static SessionEntity takeSession(SessionEntity session) throws Exception{
//		return DAOFactory.getSessionDAO().getSession(session);
//	}
//	
//	public static SessionEntity takeSession(String sessionkey) throws Exception{
//		SessionEntity session = new SessionEntity(sessionkey, null);
//		return DAOFactory.getSessionDAO().getSession(session);
//	}
//	
//	public static SessionEntity getSession(String sessionkey) throws Exception{
//		SessionEntity session = new SessionEntity(sessionkey, null);
//		return DAOFactory.getSessionDAO().getSession(session);
//	}
	
//	public long getUserId() {
//		return userId;
//	}

//	public void setUserId(long userId) {
//		
//		this.userId = userId;	
//		long time = System.currentTimeMillis();
//		long ranLong = time + userId;
//		
//		StringBuilder sb = new StringBuilder(70);
//		String strId = String.format("%020d", ranLong);
//		String strVal = WebUtil.hashEncrypt(strId);
//		
//		sb.append(strVal).append(strId);
//		
//		request.setAttribute(ServiceConstants.USER_ID.toString(), new Long(userId));
//		
//		//clear all other session cookies before set
//		Cookie [] cookies = request.getCookies();
//		if(cookies != null){
//			for(Cookie c : cookies){
//				if(c.getName() == null) continue;
//				if(c.getName().startsWith(ServiceConstants.SessionID)){
//					c.setMaxAge(0);
//					CookieHelper.setDefaultProperty(c);
//					response.addCookie(c);
//				}
//			}
//		}
//		
//		Cookie cookie = new Cookie(ServiceConstants.SessionID + time, sb.toString());
//		
//		cookie.setMaxAge(-1); //will make the cookie expire after the browser is closed
//		CookieHelper.setDefaultProperty(cookie);
////		cookie.setPath("/");
//		
//		response.addCookie(cookie);
//
//	}
	
	//for web local app, like file:///c:/user/ifortzone/index.html
	//it might not has cooke since it's local access
	
	public static long getUserIdfromMobileSession(String session){
		
		if(!isValidMobileToken(session)){
			System.out.println("无效的token:"+session);
			return 0;
		}
		
		String val=session.split(":")[1];
		long time = Long.parseLong(session.split(":")[0]);
		long mixId = Long.parseLong(val.substring(val.length() - 20, val.length()));
		String strVal = val.substring(0, val.length()-20);
		
		String strId = String.format("%020d", mixId);
		if(!strVal.equals(WebUtil.hashEncrypt(strId))){
			return 0;
		}
		
		long uid = mixId-time;
//		WebUtil.logDebug("read user id from mobile token:"+uid);
		return uid;
	}
}
